//
//  SecurityMessageViewController.m
//  LocomotiveGuards
//
//  Created by xys on 15/11/21.
//  Copyright (c) 2015年 REDOOR. All rights reserved.
//

#import "SecurityMessageViewController.h"
#import "SecurityMessageEditViewController.h"
#import "SecurityMessageCell.h"
#import "SecurityMessage.h"
#import "SecurityMessageFmdbModel.h"
#import "AlertView.h"
#import "LoginViewController.h"

static  NSString * CellTableIdentifier = @"CellTableIdentifier";//普通单元格

@interface SecurityMessageViewController ()
<UITableViewDelegate,UITableViewDataSource>
@end

@implementation SecurityMessageViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.leftbtn addTarget:self action:@selector(goBackButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    /*
        从服务器获取消息
     */
    //[self getAlarmMsgs];
    SecurityMessageFmdbModel * messageModel = [[SecurityMessageFmdbModel alloc]init];
    self.messageList = [[NSMutableArray alloc]initWithArray:[messageModel messages]];
    
    [self.centerbtn setImage:nil forState:UIControlStateNormal];
    [self.centerbtn setTitle:@"消息" forState:UIControlStateNormal];
    
    [self.rightbtn setImage:nil forState:UIControlStateNormal];
    [self.rightbtn setTitle:@"选择" forState:UIControlStateNormal];
    self.rightbtn.titleLabel.font = [UIFont systemFontOfSize:17];
    [self.rightbtn addTarget:self action:@selector(rigthButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH,CGRectGetHeight(self.view.frame)-120)];
    [self.tableView registerClass:[SecurityMessageCell class] forCellReuseIdentifier:NSStringFromClass([SecurityMessageCell class])];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.scrollsToTop = NO;
    self.tableView.alwaysBounceVertical = NO;
    self.tableView.alwaysBounceHorizontal = NO;
    self.tableView.allowsSelection = NO;
    [self.tableView setTableFooterView:[[UIView alloc]initWithFrame:CGRectZero]];
    
    [self.view addSubview:self.tableView];
    
    /*
        子类不继承该通知
     */
    if ([NSStringFromClass([self class]) isEqualToString:NSStringFromClass([SecurityMessageViewController class])])
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(messageRefreshNotificationHandler) name:SECURITY_MESSAGE_REFRESH_NOTIFICATION object:nil];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"changetabbartwo" object:nil userInfo:@{@"key":@"1"}];
    [self.tableView reloadData];
}


#pragma mark - UITableViewDelegate method -

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    /*
        获取单元格
     */
    SecurityMessageCell * cell = [tableView dequeueReusableCellWithIdentifier:@"FDFeedCell"];
    if (nil == cell)
    {
        cell = [[SecurityMessageCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"FDFeedCell" hasCheckBox:NO];
    }

    SecurityMessage * msg = [SecurityMessage SecurityMessageWithMessageDict:self.messageList[indexPath.row]];
    cell.securityMessage = msg;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary * dict = [self.messageList objectAtIndex:indexPath.row];
    NSString * str = dict[@"msg"];
    CGFloat heitht = [self calculateNSStringSize:str font:MESSAGE_MESSAGELABEL_TEXT_FRONT
 maxWidth:SCREEN_WIDTH - (SCREEN_WIDTH * 0.03+SCREEN_HEIGHT*0.03+SCREEN_HEIGHT*0.03)];
    
    return heitht + MESSAGE_DATELABEL_HEIGHT + 30;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.messageList.count;
}


#pragma mark - button clicked handler - 

- (void) goBackButtonClicked:(UIButton *) backButton
{
    [self.navigationController popToRootViewControllerAnimated:NO];
}

- (void) rigthButtonClicked:(UIButton *) rightButton
{
    if ([self.userOrTourist isEqualToString:@"1"]) {
        NSLog(@"-----rigthButtonClicked------------%@",[self class]);
        
        SecurityMessageEditViewController * securityMessageEditViewController = [[SecurityMessageEditViewController alloc]init];
        [self presentViewController:securityMessageEditViewController animated:NO completion:nil];
    }
    else {
        AlertView *alertView = [[AlertView alloc] initWithConfirmButtonBlock:^{
            NSLog(@"登录");
            LoginViewController *loginVC = [[LoginViewController alloc]init];
            [self presentViewController:loginVC animated:YES completion:nil];
        } cancelButtonBlock:^{
            NSLog(@"取消");
        }];
        [self.view addSubview:alertView];
    }
}

#pragma mark -Custom method -

/**
 *  主动获取用户车辆的告警信息
 */
#if 0
- (void) getAlarmMsgs
{
    //本地获取消息
    [self getMessagesFromLocal];
    
    //http://appif.jszhtech.com:8080/ebappif/appif/getAlarmMsgs.do?loginId=18602556151
    
    /**
     *  消息编辑界面的数据只从本地获取
     */
    if (![NSStringFromClass([self class]) isEqualToString:NSStringFromClass([SecurityMessageViewController class])])
    {
        return;
    }
    NSString * loginId = [[NSUserDefaults standardUserDefaults]objectForKey:@"phonenumber"];
    NSString * urlMethod = [NSString stringWithFormat:@"%@getAlarmMsgs.do",urlstring];
    
    [K_AppDelegate GenerateHTTPRequestWithUrl:urlMethod withParam:@{@"loginId":loginId} success:
     ^(AFHTTPRequestOperation *operation, id responseObject) {
         NSDictionary * responseDict = responseObject;
         
         NSNumber * flag = [responseObject objectForKey:@"flag"];
         if (0 == flag.longValue )
         {
             NSArray * msgList = [responseObject objectForKey:@"list"];
             
             if ( msgList && msgList.count > 0 )
             {
                 
                 [msgList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
                  {
                      /*
                         过滤掉重复的消息
                       */
                      if ( msgList[idx] && msgList[idx][@"msgId"] )
                      {
                          if (![self.msgIdList containsObject:msgList[idx][@"msgId"]])
                          {
                              [self.messageList addObject:msgList[idx]];
                              [self.msgIdList addObject:msgList[idx][@"msgId"]];
                          }
                      }
                  }];
                 [self.tableView reloadData];
                 [self saveMessagesToLocal];//后期优化：当有不同数据时才去保存到本地
             }
         }
         else
         {
             NSLog(@"%@",responseDict[@"msg"]);
         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"查询防护状态失败！");
     }];
}

#pragma mark - notification handle -

- (void) messageRefreshNotificationHandler
{
    [self getMessagesFromLocal];
}

/**
 *  获取本地消息存储文件路径
 *
 *  @return 文件路径
 */
- (NSString *) getMessagesFilePath
{
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
//    BOOL isDir = NO;
//    BOOL isExisted = [[NSFileManager defaultManager]fileExistsAtPath:paths.firstObject isDirectory:&isDir];
//    if (!(isDir == YES && isExisted == YES))
//    {
//        [[NSFileManager defaultManager] createDirectoryAtPath:paths.firstObject  withIntermediateDirectories:YES attributes:nil error:nil];
//    }
    
    NSString * messagesFilePath = [NSString stringWithFormat:@"%@/messages.plist",paths.firstObject];
    
    return messagesFilePath;
}

/**
 *  本地获取消息列表
 */
- (void) getMessagesFromLocal
{
    self.messageList = [NSMutableArray arrayWithContentsOfFile:[self getMessagesFilePath]];
    
    if (!self.messageList)
    {
        self.messageList = [[NSMutableArray alloc]init];
    }
    
    self.msgIdList = [[NSMutableArray alloc]init];
    [self.messageList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
     {
         [self.msgIdList addObject:obj[@"msgId"]];
    }];
}

/**
 *  保存消息列表至本地
 */
- (void) saveMessagesToLocal
{
    [self.messageList writeToFile:[self getMessagesFilePath] atomically:YES];
}
#endif

- (void) messageRefreshNotificationHandler
{
    SecurityMessageFmdbModel * messageModel = [[SecurityMessageFmdbModel alloc]init];
    self.messageList = nil;
    self.messageList = [[NSMutableArray alloc]initWithArray:[messageModel messages]];
}

/**
 *  获取字符串高度
 *
 *  @param text
 *  @param font  <#font description#>
 *  @param width <#width description#>
 *
 *  @return <#return value description#>
 */
- (CGFloat)calculateNSStringSize:(NSString * )text font:(UIFont *) font maxWidth:(CGFloat) width
{
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.alignment = NSTextAlignmentLeft;
    NSDictionary * attributes = @{NSFontAttributeName : font,
                                  NSParagraphStyleAttributeName : paragraphStyle};
    CGSize contentSize = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
                                            options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                         attributes:attributes
                                            context:nil].size;
    return contentSize.height;
}

@end
